package com.ruoyi.web.ydz.util.generatePDF;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板第一页不占满，生成表格
 */
@Component
public class CreatePdfEchrtsAndTableMain {

    public void ImageToPDF(List<String> urlList, HttpServletRequest request, HttpServletResponse response) {

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"images.pdf\"");

        try (OutputStream out = response.getOutputStream()) {
            PdfWriter writer = new PdfWriter(out);
            PdfDocument pdfDoc = new PdfDocument(writer);
            Document doc = new Document(pdfDoc);

            List<File> images = new ArrayList<>();
            for (String path : urlList) {
                File inputDir = new File(path);
                if (inputDir.isFile() && isImageFile(inputDir)) {
                    images.add(inputDir);
                }
            }

            // 添加每个图片到PDF
            for (File image : images) {
                byte[] imageData = Files.readAllBytes(image.toPath());
                ImageData imageDataObj = ImageDataFactory.create(imageData);
                Image img = new Image(imageDataObj);
                doc.add(img);
                doc.add(new Paragraph("\n")); // 添加间距
            }

            doc.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断给定的文件是否为图片文件
     * 将输入的文件名转化为小写字母，并将支持的图片文件后缀放入一个字符串数组中进行遍历，
     * 如果文件的后缀在支持的图片文件后缀列表内，就说明该文件是一个图片文件。否则返回false。
     *
     * @param file 文件
     * @return boolean
     */
    private static boolean isImageFile(File file) {
        String fileName = file.getName().toLowerCase();
        String[] supportedExtensions = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        for (String extension : supportedExtensions) {
            if (fileName.endsWith(extension)) {
                return true;
            }
        }
        return false;
    }
}

